package com.tyj.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tyj.common.constant.AuthServerConstant;
import com.tyj.common.exception.BizCodeEnume;
import com.tyj.common.utils.R;
import com.tyj.common.vo.MemberRespVo;
import com.tyj.gulimall.auth.feign.MemberFeignService;
import com.tyj.gulimall.auth.feign.ThirdPartFeignService;
import com.tyj.gulimall.auth.vo.UserLoginVo;
import com.tyj.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class UserController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 发送短信服务
     *
     * @param phone 手机号码
     * @return
     */
    @RequestMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        //TODO 接口防刷  验证码的再次效验
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (redisCode != null) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                //是在60秒内
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //没在60秒内 可以发送
        String code = UUID.randomUUID().toString().substring(0, 5);
        //redis缓存验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(),15,TimeUnit.MINUTES);
        log.debug("code=" + code);

        R r = null;
        try {
            r = thirdPartFeignService.sendCode(phone, code);
            if (r.getCode() == 0) {
                log.debug("远程短信服务调用成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("远程短信服务调用失败");
            return R.error(BizCodeEnume.SMS_CODE_SERVER_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_SERVER_EXCEPTION.getMsg());
        }
        return R.ok();
    }

    /**
     * 注册
     */
    @PostMapping("/regist")
    @ResponseBody
    public R regist(@Valid UserRegistVo vo, BindingResult result, Model model) {
        //校验注册数据
        Map<String, String> errors = new HashMap<>();
        if (result.hasErrors()) {
            log.debug(errors.toString());
            errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).setData(errors);
        }

        //检查验证码是否正确
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (s != null) {
            String code = s.split("_")[0];
            if (vo.getCode().equals(code)) {
                //验证码正确 调用远程服务进行注册
                R r = memberFeignService.regist(vo);
                //删除redis验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                if (r.getCode()==0){
                    //注册成功回到首页,回到登录页
                    return R.ok();
                }else {
                    //验证失败返回提示
                    if (r.getCode()==20001){
                        errors.put("phone",r.get("msg").toString());
                    }else if (r.getCode()==20002){
                        errors.put("userName",r.get("msg").toString());
                    }
                    log.debug(errors.toString());
                    return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).setData(errors);
                }
            } else {
                //验证码错误
                errors.put("code", "验证码不正确");
                log.debug(errors.toString());
                return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).setData(errors);
            }
        }else {
            errors.put("code","你尚未发送验证码");
            log.debug(errors.toString());
            return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).setData(errors);

        }
    }

    /**
     * 登录
     * @param vo
     * @param session
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public R login(UserLoginVo vo, HttpSession session){
        R r = memberFeignService.login(vo);
        if (r.getCode()==0){
            //存入session并返回
            MemberRespVo data = r.getData(new TypeReference<MemberRespVo>(){});
            log.debug("存放session对象数据="+data);
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return r;
        }else {
            return r;
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        if (session.getAttribute(AuthServerConstant.LOGIN_USER)==null) {
        //没登录
        return "login";
        }
        return "redirect:http://gulimall.com";
    }

    @GetMapping("/exitLogin")
    public String exitLogin(HttpSession session){
        //刪除session数据
        session.removeAttribute(AuthServerConstant.LOGIN_USER);
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @GetMapping("/deleteLoginMsg")
    public R deleteLoginMsg(HttpSession session){
        session.removeAttribute("msg");
        return R.ok();
    }


}
